<?php

namespace App\Http\Controllers;

use App\Common\HttpClient;
use App\Common\Logger;
use App\Common\Sql;
use App\Common\Tool;
use App\Exceptions\ApiException;
use App\Logic\LoginLogic;
use App\Logic\RegisterLogic;
use Illuminate\Support\Facades\DB;

class WxLogin extends Base
{

    /**
     * @return string
     * @throws \App\Exceptions\ApiException
     */
    public function logic()
    {
        //微信号
        if (!isset($this->param['wx_id'])) {
            $this->returnError(330, "wx_id must be needed");
        } else {
            $wx_id = $this->param['wx_id'];
        }

        //微信昵称
        $nick_name = $this->param['nick_name'] ?? '';
        //微信头像URL
        $avater_url = $this->param['avater_url'] ?? '';
        //微信性别
        $sex = $this->param['sex'] ?? '';

        //手机型号
        if (!isset($this->param['ua'])) {
            $ua = "";
        } else if (strlen($this->param['ua']) > 20) {
            $ua = substr($this->param['ua'], 0, 20);
        } else {
            $ua = $this->param['ua'];
        }

        //该微信ID是否已经注册，如果是直接登录，如果不是注册
        $row = Sql::select('t_player_info', [['wx_id', $wx_id]]);
        if (count($row) >= 1) {
            //该微信号已经注册过，直接登录
            if ($row[0]['status'] == 0) { //被禁号
                throw new ApiException('您的账号已经被管理员封禁，如有疑问请联系客服', 120);
            }
            //CDN地址的用户头像
            $new_avater_url       = (new HttpClient())->Get('http://test.heroscocks.com/saveWeChatAvaterUrl?' . 'wx_id=' . $wx_id . '&avater_url=' . $avater_url . '&key=' . sha1($wx_id . $avater_url));
//            $new_avater_url       = (new HttpClient())->Get('http://gz.com/saveWeChatAvaterUrl?' . 'wx_id=' . $wx_id . '&avater_url=' . $avater_url . '&key=' . sha1($wx_id . $avater_url));
            $row[0]['type']       = 2;
            $row[0]['avater_url'] = $new_avater_url;
            return $this->returnData(LoginLogic::instance()->postPosition($row[0]));
        } elseif (count($row) == 0) {
            return $this->returnData(
                RegisterLogic::instance()->handle([
                    'is_check_phone' => 0,
                    'nick_name' => $nick_name,
                    'password' => rand(100000, 999999),
                    'ua' => $ua,
                    'type' => 2,
                    'wx_id' => $wx_id,
                    'sex' => $sex,
                    'avater_url' => $avater_url
                ])
            );
        }
    }
}
